# -*- coding: utf8 -*-

from __future__ import absolute_import, unicode_literals
import os
from flask import Flask, request, abort, render_template
from wechatpy.enterprise.crypto import WeChatCrypto
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.enterprise.exceptions import InvalidCorpIdException
from wechatpy.enterprise import parse_message, create_reply
from wechatpy import WeChatClient
from wechatpy.enterprise.client.api import WeChatMessage
from wechatpy.enterprise import WeChatClient

import db
from selenium import webdriver
import requests
import random
import string
import time
import json
from datetime import datetime, timedelta
import hashlib



TOKEN = os.getenv('WECHAT_TOKEN', 'WxmqchjNhZ4Gg5BYkdB0tlzhwjZ')
EncodingAESKey = os.getenv('WECHAT_ENCODING_AES_KEY', 'PIU7ngAqiYQvWfHlivg3NkMFGYmc6qkxcg1eLD67pMr')
CorpId = os.getenv('WECHAT_CORP_ID', 'wxa355b9041c07a137')
Secret = os.getenv('WECHAT_SECRET', 'C9zcHMDbPCUvJ4zd-DlUY0aoPXL4wcl9TpB7qJW4GNA')
Agentid = os.getenv('WECHAT_AGENTID', '49')

class Sign:
    def __init__(self, jsapi_ticket, url):
        self.ret = {
            'nonceStr': self.__create_nonce_str(),
            'jsapi_ticket': jsapi_ticket,
            'timestamp': self.__create_timestamp(),
            'url': url
        }

    def __create_nonce_str(self):
        return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))

    def __create_timestamp(self):
        return int(time.time())

    def sign(self):
        string = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)])
        print '0000000000000000000000000000'
        print (string)
        self.ret['signature'] = hashlib.sha1(string.encode('utf-8')).hexdigest()
        return self.ret


app = Flask(__name__)
@app.route('/',methods=['GET', 'POST'])
def test():
    at_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (CorpId ,Secret)
    r = requests.get(at_url)
    res = r.json()
    access_token = res['access_token']

    ticket_url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s" % (access_token)
    r = requests.get(ticket_url)
    res = r.json()

    nonceStr = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))
    timestamp = int(time.time())



    code = request.args.get('code', '')
    uid_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s" % (access_token ,code)
    r = requests.get(uid_url)
    res = r.json()
    print '---------------------'
    print code
    UserId = res['UserId']
    c = db.BIDbQuery()
    abc = '你好你好dzy'
    client = WeChatClient(corp_id=CorpId,secret=Secret)
    #最新截止日期
    title = "查询用户id"
    content = "UserId"
    UserId = UserId

    client.message.send_text("44", 'dzy', content=u"标题:{0}\n 内容:{1}\n id号:{2}".format(title, content, abc))
    data = c.get_data()
    return render_template('test.html', 
            data = data,
            CorpId = CorpId
            )

@app.route('/jssdkconfig',methods=['GET', 'POST'])
def jssdk_config():
    at_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (CorpId ,Secret)
    r = requests.get(at_url)
    res = r.json()
    access_token = res['access_token']

    signa_url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s" %(access_token)
    r = requests.get(signa_url)
    res = r.json()
    ticket = res['ticket']
    print '-------------------------------------'
    print ticket
    print '-------------------------------------'

    HTML_URL = "https://dzy.pagekite.me/jssdkconfig#menu-shopping"
    ticket = ticket#具体获取方法见最上方连接文章

    sign = Sign(ticket, HTML_URL)
    result = {

        "result":sign.sign()

    }
    print 'xxxxxxxxxxxxxxxxxxxxxxx'
    print result['result']['signature']
    print 'xxxxxxxxxxxxxxxx'
#响应头 允许跨域访问
    response_heade = {
        'Access-Control-Allow-Origin' : '*'
    }
    return render_template('demo.html', 
            sig = result
            )

    #return make_response(json.dumps(result).encode("utf-8"),200,response_heade)

if __name__ == '__main__':
    app.run('0.0.0.0', debug=True)
